/*
 * MIT License
 *
 * Copyright (c) 2019 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package cn.seaboot.commons.handler;

import cn.seaboot.commons.exception.HandlerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;

/**
 * 消息队列处理器，内部绑定一个队列
 *
 * @author Mr.css on 2018年2月1日
 */
public abstract class Handler {
    private final Logger logger = LoggerFactory.getLogger(Handler.class);
    private final BlockingQueue<Message> queue;

    /**
     * 在构造 handler 的时候，会自动关联上 ThreadLocal 中的 looper，
     * 因此必须确保当前线程中已经存在 looper，handler 发送的消息，
     * 最终都能被 looper 内部维护的工作线程处理。
     */
    public Handler() {
        Looper looper = Looper.myLooper();
        if (looper == null) {
            throw new HandlerException("Can't create handler inside thread that has not called Looper.prepare()");
        }
        this.queue = looper.queue;
    }

    /**
     * 绑定到一个消息队列中，注意将消息队列绑定到 Looper 中。
     *
     * @param queue 与 Looper 绑定的队列
     */
    public Handler(BlockingQueue<Message> queue) {
        this.queue = queue;
    }


    /**
     * 添加一条消息到消息队列，delayMillis为0不代表会被工作线程立即执行，如果队列上的任务过多，任务依然会进入长时间等待
     *
     * @param msg 消息
     * @return 是否成功添加到队列中
     */
    public final boolean sendMessage(Object msg) {
        return sendMessage(msg, 0);
    }

    /**
     * 如果需要定制消息拒绝策略，获取消息队列大小的功能还是非常有必要的
     *
     * @return size of message queue
     */
    public int queueSize(){
        return queue.size();
    }

    /**
     * 添加一条消息到消息队列
     *
     * @param msg         消息
     * @param delayMillis 消息延迟时间，消息从放到队列，到被工作线程处理，这个时间段可能会大于delayMillis，
     *                    如果工作线程上等待的任务过多，消息会一直排队等待处理，
     *                    为了避免问题，消息的任务处理，可以使用异步执行。
     * @return 是否成功添加到队列中
     */
    public boolean sendMessage(Object msg, long delayMillis) {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, delayMillis);
    }


    /**
     * 放置一个哑元元素，侦听到哑元元素之后，就会中断轮询任务
     *
     * @return 是否成功添加到队列中
     */
    public final boolean sendDummy() {
        return sendMessageAtTime(Message.dummy(), 0);
    }

    /**
     * 添加一条消息到消息队列
     *
     * @param msg         消息
     * @param delayMillis 即使值为0，也不会立即执行，消息都会被添加到队列中，等待工作线程处理
     * @return 是否成功添加到队列中
     */
    private boolean sendMessageAtTime(Object msg, long delayMillis) {
        BlockingQueue<Message> q = queue;
        if (q == null) {
            throw new HandlerException(this + " sendMessageAtTime() called with no mQueue");
        }
        Message item;
        if (msg instanceof Message) {
            item = (Message) msg;
            item.setHandler(this);
            item.setTimeout(delayMillis);
        } else {
            item = new Message(msg, this, delayMillis);
        }
        try {
            q.put(item);
            return true;
        } catch (InterruptedException e) {
            logger.debug("Handler.sendMessageAtTime() cause any exception: ", e);
            return false;
        }
    }

    /**
     * 触发回执函数
     *
     * @param msg 消息
     */
    final void dispatchMessage(Object msg) {
        handleMessage(msg);
    }

    /**
     * 处理一则消息的回调函数
     *
     * @param msg 消息
     */
    abstract public void handleMessage(Object msg);
}